/**
 * 
 */
package com.m7012e.a_remote.ar_stub.old;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author leoj
 *
 */
public abstract class NetworkThread extends Thread {
	private ServerSocket _svrSocket;
	private MulticastSocket _multiSocket;
	private boolean _running;
	
	public NetworkThread(int port, int timeout, String multicastAddress){
		super();
		try{
			_svrSocket = new ServerSocket(port);
			_svrSocket.setSoTimeout(timeout);
		} catch (IOException e){
			System.err.println("error with the server socket");
			e.printStackTrace();
		}
		try {
			_multiSocket= new MulticastSocket();
			_multiSocket.joinGroup(InetAddress.getByName(""));
		} catch (IOException e) {
			System.err.println("error with the multicast socket");
			e.printStackTrace();
		}
		
	}
	public NetworkThread(int port, String multicastAddress){
		this(port, 3000, multicastAddress);
	}
	public NetworkThread(){
		this(8706, "255.5.6.7");
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		super.run();
		_running = true;
		Socket socket;
		while(_running){
			try {
				socket = _svrSocket.accept();
				handleNewConnection(socket);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	abstract protected void handleNewConnection(Socket s);
	
	public void stopASAP(){ _running = false; }
	public void broadcastMessage(){
		
	}
}
